package com.aloda.service.impl;

import com.aloda.constant.ExceptionConstant;
import com.aloda.constant.SaltConstant;
import com.aloda.constant.UserConstant;
import com.aloda.exception.AuthException;
import com.aloda.exception.BaseException;
import com.aloda.mapper.UserMapper;
import com.aloda.pojo.dto.*;
import com.aloda.pojo.entity.User;
import com.aloda.pojo.vo.UserLoginVO;
import com.aloda.pojo.vo.UserPageVO;
import com.aloda.result.PageResult;
import com.aloda.service.UserService;
import com.aloda.utils.RegexUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO, HttpServletRequest request) {
        // 校验用户名密码合法性
        if (!RegexUtils.checkEmail(userLoginDTO.getEmail())) {
            throw new BaseException(ExceptionConstant.EMAIL_ERROR);
        }
        if (!RegexUtils.checkPassword(userLoginDTO.getPassword())) {
            throw new BaseException(ExceptionConstant.PASSWORD_ERROR);
        }
        // 校验用户名密码输入是否正确
        userLoginDTO.setPassword(DigestUtils.md5DigestAsHex((userLoginDTO.getPassword() + SaltConstant.PASSWORD_SALT).getBytes()));
        User user = userMapper.SelectUserByUnAndPw(userLoginDTO);
        if (user == null) {
            // 用户名或者密码错误
            throw new BaseException(ExceptionConstant.LOGIN_ERROR);
        }
        if (UserConstant.STATUS_BANNED.equals(user.getStatus())) {
            // 该账号被禁用
            throw new BaseException(ExceptionConstant.ACCOUNT_BANNED);
        }
        // 添加session
        UserSafetyDTO userSafetyDTO = new UserSafetyDTO();
        BeanUtils.copyProperties(user,userSafetyDTO);
        request.getSession().setAttribute(UserConstant.USER_SESSION_KEY, userSafetyDTO);
        // 返回VO对象
        return UserLoginVO.builder()
                .id(user.getId())
                .name(user.getName())
                .role(user.getRole())
                .build();
    }

    /**
     * 分页查询用户
     *
     * @param userPageDTO
     * @return
     */
    @Override
    public PageResult<UserPageVO> getUserPage(UserPageDTO userPageDTO) {
        PageHelper.startPage(userPageDTO.getCurrentPage(), userPageDTO.getPageSize());
        Page<User> page = userMapper.selectPage(userPageDTO);
        // 用户信息脱敏
        List<UserPageVO> voList = page.getResult()
                .stream()
                .map(user -> {
                    UserPageVO userPageVO = new UserPageVO();
                    BeanUtils.copyProperties(user, userPageVO);
                    return userPageVO;
                })
                .collect(Collectors.toList());
        return new PageResult<>(page.getTotal(), voList);
    }

    /**
     * 新增用户
     *
     * @param userAddDTO
     */
    @Override
    public void addUser(UserAddDTO userAddDTO) {
        // 格式校验
        if(!RegexUtils.checkName(userAddDTO.getName())) {
            throw new BaseException(ExceptionConstant.NAME_ERROR);
        }
        if (!RegexUtils.checkEmail(userAddDTO.getEmail())) {
            throw new BaseException(ExceptionConstant.EMAIL_ERROR);
        }
        if (!RegexUtils.checkPassword(userAddDTO.getPassword())) {
            throw new BaseException(ExceptionConstant.PASSWORD_ERROR);
        }
        // 校验邮箱是否已注册
        User result = userMapper.selectUserByUn(userAddDTO.getEmail());
        if (result != null) {
            throw new BaseException(ExceptionConstant.EMAIL_IS_REGISTERED);
        }
        // 创建用户对象
        User user = new User();
        user.setName(userAddDTO.getName());
        user.setPassword(DigestUtils.md5DigestAsHex((userAddDTO.getPassword() + SaltConstant.PASSWORD_SALT).getBytes()));
        user.setEmail(userAddDTO.getEmail());
        user.setStatus(UserConstant.STATUS_USABLE);
        user.setRole(userAddDTO.getRole());
        user.setHiredate(LocalDate.now().toString());
        userMapper.insert(user);
    }

    /**
     * 修改用户状态
     *
     * @param status
     */
    @Override
    public void setUserStatus(String status,Integer id) {
        if (UserConstant.SUPER_ADMIN_ID == id) {
            throw new AuthException(ExceptionConstant.EDIT_ADMIN_ERROR);
        }
        User user = userMapper.selectUserById(id);
        user.setStatus(status);
        userMapper.update(user);
    }

    /**
     * 通过id获取用户信息
     *
     * @param id
     * @return
     */
    @Override
    public UserPageVO getUserInfo(Integer id) {
        UserPageVO userPageVO = new UserPageVO();
        User user = userMapper.selectUserById(id);
        // 用户信息脱敏
        BeanUtils.copyProperties(user,userPageVO);
        return userPageVO;
    }

    /**
     * 编辑用户信息
     *
     * @param userEditDTO
     */
    @Override
    public void editUser(UserEditDTO userEditDTO) {
        // 格式校验
        if (!RegexUtils.checkEmail(userEditDTO.getEmail())) {
            throw new BaseException(ExceptionConstant.EMAIL_ERROR);
        }
        if(!RegexUtils.checkName(userEditDTO.getName())) {
            throw new BaseException(ExceptionConstant.NAME_ERROR);
        }
        if(UserConstant.SUPER_ADMIN_ID == userEditDTO.getId()) {
            throw new BaseException(ExceptionConstant.EDIT_ADMIN_ERROR);
        }
        // 校验邮箱是否已注册
        User result = userMapper.selectUserByUn(userEditDTO.getEmail());
        if (result != null && !result.getId().equals(userEditDTO.getId())) {
            throw new BaseException(ExceptionConstant.EMAIL_IS_REGISTERED);
        }
        // 更新用户信息
        User user = new User();
        BeanUtils.copyProperties(userEditDTO,user);
        userMapper.update(user);
    }
}
